package cn.xyz.it.ExcelUtil.excel;

import org.apache.commons.lang3.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;

import java.beans.Expression;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReflectUtil {

    private static final Log logger = LogFactory.getLog(ReflectUtil.class);

    private static final String SETTER_PREFIX = "set";

    private static final String GETTER_PREFIX = "get";

    private static final String CGLIB_CLASS_SEPARATOR = "$$";


    /**
     * 调用Getter方法.
     * 支持多级，如：对象名.对象名.方法
     */
    public static Object invokeGetter(Object obj, String propertyName) {
        Object object = obj;
        for (String name : org.apache.commons.lang3.StringUtils.split(propertyName, ".")) {
            String getterMethodName = GETTER_PREFIX + org.apache.commons.lang3.StringUtils.capitalize(name);
            object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
        }
        return object;
    }

    /**
     * 调用Setter方法, 仅匹配方法名。
     * 支持多级，如：对象名.对象名.方法
     */
    public static void invokeSetter(Object obj, String propertyName, Object value) {
        Object object = obj;
        String[] names = org.apache.commons.lang3.StringUtils.split(propertyName, ".");
        for (int i = 0; i < names.length; i++) {
            if (i < names.length - 1) {
                String getterMethodName = GETTER_PREFIX + org.apache.commons.lang3.StringUtils.capitalize(names[i]);
                object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
            } else {
                String setterMethodName = SETTER_PREFIX + org.apache.commons.lang3.StringUtils.capitalize(names[i]);
                invokeMethodByName(object, setterMethodName, new Object[]{value});
            }
        }
    }

    /**
     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
     */
//	public static Object getFieldValue(final Object obj, final String fieldName) {
//		Field field = getAccessibleField(obj, fieldName);
//
//		if (field == null) {
//			throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
//		}
//
//		Object result = null;
//		try {
//			result = field.get(obj);
//		} catch (IllegalAccessException e) {
//			logger.error("不可能抛出的异常{}", e.getMessage());
//		}
//		return result;
//	}

    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */
    public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
        }

        try {
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            logger.error(e.toString());
        }
    }

    /**
     * 直接调用对象方法, 无视private/protected修饰符.
     * 用于一次性调用的情况，否则应使用getAccessibleMethod()函数获得Method后反复调用.
     * 同时匹配方法名+参数类型，
     */
    public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
                                      final Object[] args) {
        Method method = getAccessibleMethod(obj, methodName, parameterTypes);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    /**
     * 直接调用对象方法, 无视private/protected修饰符，
     * 用于一次性调用的情况，否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
     * 只匹配函数名，如果有多个同名函数调用第一个。
     */
    public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
        Method method = getAccessibleMethodByName(obj, methodName);
        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
        }

        try {
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw convertReflectionExceptionToUnchecked(e);
        }
    }

    /**
     * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
     * <p>
     * 如向上转型到Object仍无法找到, 返回null.
     */
    public static Field getAccessibleField(final Object obj, final String fieldName) {
        Validate.notNull(obj, "object can't be null");
        Validate.notBlank(fieldName, "fieldName can't be blank");
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(fieldName);
                makeAccessible(field);
                return field;
            } catch (NoSuchFieldException e) {//NOSONAR
                // Field不在当前类定义,继续向上转型
                continue;// new add
            }
        }
        return null;
    }

    /**
     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     * 匹配函数名+参数类型。
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethod(final Object obj, final String methodName,
                                             final Class<?>... parameterTypes) {
        Validate.notNull(obj, "object can't be null");
        Validate.notBlank(methodName, "methodName can't be blank");

        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
            try {
                Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
                makeAccessible(method);
                return method;
            } catch (NoSuchMethodException e) {
                // Method不在当前类定义,继续向上转型
                continue;// new add
            }
        }
        return null;
    }

    /**
     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
     * 如向上转型到Object仍无法找到, 返回null.
     * 只匹配函数名。
     * <p>
     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
     */
    public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
        Validate.notNull(obj, "object can't be null");
        Validate.notBlank(methodName, "methodName can't be blank");

        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
            Method[] methods = searchType.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    makeAccessible(method);
                    return method;
                }
            }
        }
        return null;
    }

    public static <T> void makeAccessible(Constructor<T> ctor) {
        if (!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
            ctor.setAccessible(true);
        }
    }
    /**
     * 改变private/protected的方法为public，尽量不调用实际改动的语句，避免JDK的SecurityManager抱怨。
     */
//	public static void makeAccessible(Method method) {
//		if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
//				&& !method.isAccessible()) {
//			method.setAccessible(true);
//		}
//	}

    /**
     * 改变private/protected的成员变量为public，尽量不调用实际改动的语句，避免JDK的SecurityManager抱怨。
     */
//	public static void makeAccessible(Field field) {
//		if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
//				.isFinal(field.getModifiers())) && !field.isAccessible()) {
//			field.setAccessible(true);
//		}
//	}

    /**
     * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
     * 如无法找到, 返回Object.class.
     * eg.
     * public UserDao extends HibernateDao<User>
     *
     * @param clazz The class to introspect
     * @return the first generic declaration, or Object.class if cannot be determined
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getClassGenricType(final Class clazz) {
        return getClassGenricType(clazz, 0);
    }

    /**
     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
     * 如无法找到, 返回Object.class.
     * <p>
     * 如public UserDao extends HibernateDao<User,Long>
     *
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic ddeclaration,start from 0.
     * @return the index generic declaration, or Object.class if cannot be determined
     */
    public static Class getClassGenricType(final Class clazz, final int index) {

        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                    + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;
        }

        return (Class) params[index];
    }

    public static Class<?> getUserClass(Object instance) {
        Assert.notNull(instance, "Instance must not be null");
        Class clazz = instance.getClass();
        if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
            Class<?> superClass = clazz.getSuperclass();
            if (superClass != null && !Object.class.equals(superClass)) {
                return superClass;
            }
        }
        return clazz;

    }

    /**
     * 将反射时的checked exception转换为unchecked exception.
     */
    public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
        if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
                || e instanceof NoSuchMethodException) {
            return new IllegalArgumentException(e);
        } else if (e instanceof InvocationTargetException) {
            return new RuntimeException(((InvocationTargetException) e).getTargetException());
        } else if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        }
        return new RuntimeException("Unexpected Checked Exception.", e);
    }

    public static Field[] getFields(Object target) {
        if (target == null)
            return null;
        Class<? extends Object> clazz = target.getClass();
        Field[] fields = clazz.getDeclaredFields();

        return fields;
    }


    /**
     * 根据class名字，调用默认的无参构造函数实例化对象
     *
     * @param className 类名
     * @return 实例
     */
    public static Object newInstance(String className) {
        Assert.notNull(className, "ClassName must not be null");
        try {
            return Class.forName(className).newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot create " + className + ": " + e.getMessage());
        }
    }

    /**
     * 实例化对象
     */
    public static <T> T newInstance(Class<T> clazz) {
        Assert.notNull(clazz, "Class must not be null");
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot create " + clazz.getName() + ": " + e.getMessage());
        }
    }

    /**
     * 根据class名字，调用默认的无参构造函数实例化对象
     *
     * @param className 类名
     * @param args      构造函数的参数
     * @return 实例
     */
    public static Object newInstance(String className, Object... args) {
        Assert.notNull(className, "ClassName must not be null");
        Class<?> clazz = null;
        try {
            clazz = Class.forName(className);
        } catch (Exception e) {
            throw new RuntimeException("Cannot find class with name" + className + ": " + e.getMessage());
        }
        return newInstance(clazz, args);
    }

    /**
     * 实例化对象。根据参数类型自动找到Constructor，并完成调用。
     *
     * @param clazz 类
     * @param args  构造函数的参数
     * @return 实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(Class<T> clazz, Object... args) {
        Expression expression = new Expression(clazz, "new", args);
        try {
            return (T) expression.getValue();
        } catch (Exception e) {
            throw new RuntimeException("Cannot create " + clazz.getName() + ": " + e.getMessage());
        }
    }


    /**
     * 调用没有参数的方法,任何类型的访问域都可以调用
     *
     * @param method 方法
     * @param target 方法所属的对象
     * @return 方法调用的返回值
     */
    public static Object invokeMethod(Method method, Object target) {
        return invokeMethod(method, target, (Object[]) null);
    }

    /**
     * 调用方法,任何类型的访问域都可以调用
     *
     * @param method 方法
     * @param target 方法所属的对象
     * @param args   参数可以是1至多个对象，或者对象数组
     * @return 方法调用的返回值
     */
    public static Object invokeMethod(Method method, Object target, Object... args) {
        makeAccessible(method);
        try {
            return method.invoke(target, args);
        } catch (Exception ex) {
            handleReflectionException(ex);
        }
        throw new IllegalStateException("Should never get here");
    }

    /**
     * 调用对象的public方法
     */
    public static Object invokePublicMethod(Object target, String methodName, Object[] arguments) {
        Expression expression = new Expression(target, methodName, arguments);
        try {
            return expression.getValue();
        } catch (Exception e) {
            handleReflectionException(e);
        }
        throw new IllegalStateException("Should never get here");
    }

    public static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
            field.setAccessible(true);
        }
    }

    public static void makeAccessible(Method method) {
        if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
            method.setAccessible(true);
        }
    }


    public static void handleReflectionException(Exception ex) {
        if (ex instanceof NoSuchMethodException)
            throw new IllegalStateException("Method not found: " + ex.getMessage());
        if (ex instanceof IllegalAccessException)
            throw new IllegalStateException("Could not access method: " + ex.getMessage());
        if (ex instanceof InvocationTargetException) {
            handleInvocationTargetException((InvocationTargetException) ex);
        }
        if (ex instanceof RuntimeException)
            throw (RuntimeException) ex;
        handleUnexpectedException(ex);
    }

    public static void handleInvocationTargetException(InvocationTargetException ex) {
        rethrowRuntimeException(ex.getTargetException());
    }

    public static void rethrowRuntimeException(Throwable ex) {
        if (ex instanceof RuntimeException)
            throw (RuntimeException) ex;
        if (ex instanceof Error)
            throw (Error) ex;
        handleUnexpectedException(ex);
    }

    private static void handleUnexpectedException(Throwable ex) {
        // Needs to avoid the chained constructor for JDK 1.4 compatibility.
        IllegalStateException isex = new IllegalStateException("Unexpected exception thrown");
        isex.initCause(ex);
        throw isex;
    }

    public static Object invokeReadMethod(Object target, String propertyName) {
        Method method = getReadMethod(target.getClass(), propertyName);
        Assert.notNull(method, "Could not find ReadMethod of field[" + propertyName + "] on target [" + target.getClass().getName() + "]");
        return invokeMethod(method, target);
    }

    /**
     * 从class以及其父类中,根据属性名获取JavaBean的'读'方法。<br/>
     * 如果属性类型是boolean，则获取的方法形式是is+属性名，否则是"get"+属性名的形式。
     */
    public static Method getReadMethod(Class clazz, String propertyName) {
        PropertyDescriptor pdescriptor = getPropertyDescriptor(clazz, propertyName);
        return pdescriptor == null ? null : pdescriptor.getReadMethod();
    }

    /**
     * 从class以及其父类中,根据属性名获取JavaBean的写方法。<br/>
     * 获取的写方法名字是"set"+属性名的形式。
     *
     * @param clazz        类
     * @param propertyName 属性名
     * @return JavaBean 的写方法
     */
    public static Method getWriteMethod(Class clazz, String propertyName) {
        PropertyDescriptor pdescriptor = getPropertyDescriptor(clazz, propertyName);
        return pdescriptor == null ? null : pdescriptor.getWriteMethod();
    }

    /**
     * 获取给定class以及其父类中的全部属性描述信息
     *
     * @param clazz 类
     * @return 全部属性描述信息
     */
    public static PropertyDescriptor[] getPropertyDescriptors(Class clazz) {
        return BeanUtils.getPropertyDescriptors(clazz);
    }

    /**
     * 根据属性名，获取给定class以及其父类中的属性描述信息
     *
     * @param clazz        类
     * @param propertyName 属性名
     * @return 属性描述信息
     */
    public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {
        return BeanUtils.getPropertyDescriptor(clazz, propertyName);
    }

    /**
     * 从class以及其父类中获取指定名字的Field，包括公共、保护、默认（包）访问和私有字段。
     *
     * @param clazz     类
     * @param fieldName 属性名
     * @return
     */
    public static Field getDeclaredField(Class<?> clazz, String fieldName) {
        return ReflectionUtils.findField(clazz, fieldName);
    }

    /**
     * 从class以及其父类中获取指定名字的Field，包括公共、保护、默认（包）访问和私有字段。
     *
     * @param clazz     类
     * @param fieldName 属性名
     * @param type      属性类型
     * @return
     */
    public static Field getDeclaredField(Class<?> clazz, String fieldName, Class<?> type) {
        return ReflectionUtils.findField(clazz, fieldName, type);
    }

    /**
     * 获取所有的属性，包括自己以及父类中 公共、保护、默认（包）访问和私有字段。
     *
     * @param clazz 类
     * @return
     */
    public static Field[] getDeclaredFields(final Class clazz) {
        Assert.notNull(clazz, "clazz不能为空");
        List<Field> fields = new ArrayList<Field>();
        for (Class<?> type = clazz; type != Object.class; type = type
                .getSuperclass()) {
            fields.addAll(Arrays.asList(type.getDeclaredFields()));
        }
        return fields.toArray(new Field[fields.size()]);
    }

    /**
     * 获取目标对象上指定属性对象的值
     *
     * @param field  属性对象
     * @param target 目标对象
     * @return 目标对象上指定属性对象的值
     */
    public static Object getFieldValue(Object target, Field field) {
        makeAccessible(field);
        return ReflectionUtils.getField(field, target);
    }

    /**
     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
     */
    public static Object getFieldValue(final Object object, final String fieldName) {
        Field field = getDeclaredField(object.getClass(), fieldName);
        Assert.notNull(field, "Could not find field [" + fieldName + "] on target [" + object + "]");
        return getFieldValue(object, field);
    }

//	public static Object getFieldValue(Object target,String name){
//
//		if(target == null || name == null || ".".equals(name)){
//			return null;
//		}
//		Class<? extends Object> clazz = target.getClass();
//		try{
//			String methodName = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
//			Method method = clazz.getDeclaredMethod(methodName);
//
//			if(!Modifier.isPublic(method.getModifiers()))
//				method.setAccessible(true);
//
//			return method.invoke(target);
//		}catch(Exception e){
//			try{
//				Field field = null;
//				while(field == null){
//
//					try{
//						field = clazz.getDeclaredField(name);
//					}catch(Exception em){
//
//					}
//					if(field == null)
//						clazz = clazz.getSuperclass();
//				}
//				if(!Modifier.isPublic(field.getModifiers()))
//					field.setAccessible(true);
//				return field.get(target);
//			}catch(Exception ex){
//			}
//			//e.printStackTrace();
//		}
//		return null;
//	}

    /**
     * 获取目标对象上指定属性对象的值
     *
     * @param field  属性对象
     * @param target 目标对象
     * @return 目标对象上指定属性对象的值
     */
    public static void setFieldValue(Field field, Object target, Object value) {
        makeAccessible(field);
        ReflectionUtils.setField(field, target, value);
    }

    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */
//	public static void setFieldValue(final Object object, final String fieldName, final Object value) {
//		Field field = getDeclaredField(object.getClass(), fieldName);
//		Assert.notNull(field, "Could not find field [" + fieldName + "] on target [" + object + "]");
//		setFieldValue(field, object, value);
//	}

//	public static void setFieldValue(Object target, String name, Object value) {
//		if (target == null || name == null || "".equals(name) || (value == null)) {
//			return;
//		}
//		Class<? extends Object> clazz = target.getClass();
//
//		try {
//			Method method = clazz.getDeclaredMethod("set" + Character.toUpperCase(name.charAt(0)) + name.substring(1));
//
//			if (!Modifier.isPublic(method.getModifiers())) {
//				method.setAccessible(true);
//			}
//			method.invoke(target, value);
//
//		} catch (Exception e) {
//			if (logger.isDebugEnabled()) {
//				logger.debug(e.toString());
//			}
//			try {
//				Field field = clazz.getDeclaredField(name);
//				if (!Modifier.isPublic(field.getModifiers())) {
//					field.setAccessible(true);
//				}
//				field.set(target, value);
//			} catch (Exception fe) {
//				if (logger.isDebugEnabled()) {
//					logger.debug(fe.toString());
//				}
//			}
//		}
//	}

    /**
     * 根据名字、参数类型从class以及其父类中获取相应的方法，包括公共、保护、默认（包）访问和私有方法。
     *
     * @param clazz      类
     * @param methodName 方法名
     * @param
     * @return
     */
    public static Method getDeclaredMethod(Class<?> clazz, String methodName, Class<?>[] paramTypes) {
        return ReflectionUtils.findMethod(clazz, methodName, paramTypes);
    }

    /**
     * 根据名字，从class以及其父类中获取相应的方法，包括公共、保护、默认（包）访问和私有方法。
     *
     * @param clazz      类
     * @param methodName 方法名
     * @return
     */
    public static Method getDeclaredMethod(Class<?> clazz, String methodName) {
        return ReflectionUtils.findMethod(clazz, methodName, (Class<?>[]) null);
    }

    /**
     * 通过反射,获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao extends HibernateDao<User>
     *
     * @param clazz The class to introspect
     * @return the first generic declaration, or Object.class if cannot be determined
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射,获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
     * <p>
     * 如public UserDao extends HibernateDao<User,Long>
     *
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic ddeclaration,start from 0.
     * @return the index generic declaration, or Object.class if cannot be determined
     */
    public static Class getSuperClassGenricType(final Class clazz, final int index) {

        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType))
            //			logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
            return Object.class;

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0)
            //			logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
//					+ params.length);
            return Object.class;
        if (!(params[index] instanceof Class))
            //			logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;

        return (Class) params[index];
    }

    public static Class<?> getFiledGenricType(final Field field, final int index) {

        Type genType = field.getGenericType();

        if (!(genType instanceof ParameterizedType))
            //			logger.warn(field.getName() + "'s field not ParameterizedType");
            return Object.class;

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0)
            //			logger.warn("Index: " + index + ", Size of " + field.getName() + "'s Parameterized Type: " + params.length);
            return Object.class;
        if (!(params[index] instanceof Class<?>))
            //			logger.warn(field.getName() + " not set the actual class on superclass generic parameter");
            return Object.class;

        return (Class<?>) params[index];
    }
}
